package com.gemme.gemme.gwc;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.R;
import com.gemme.gemme.fragment.BaseLazyFragment;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.GwcEditView;
import com.gemme.gemme.view.GwcItemView;
import com.gemme.gemme.view.OnChangeLIstener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by sp on 2019/7/18.
 * 首页
 */
public class GwcNewFragment extends BaseLazyFragment implements View.OnClickListener {

    View inflate;
    Context mContext;
    boolean isEdit = false;
    GwcEditView gwcEditView;
    TextView tv_eidt;
    LinearLayout ll_content;
    ScrollView scroll_view;
    View.OnClickListener allClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    };
    List<GwcBean2.DataBean.RecordsBean> records;
    boolean isAllSelet = false;
    ArrayList<GwcBean2.DataBean.RecordsBean> selectData = new ArrayList<>();
    //商店商品是否全选
    OnChangeLIstener onitemChangeLIstener = new OnChangeLIstener() {
        @Override
        public void onChangeLIstener() {
//            gwcEditView.
            isAllSelet();
            setSumPrice();
            gwcEditView.getCheckbox().setChecked(isAllSelet);
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        inflate = inflater.inflate(R.layout.fragment_gwc_new, container, false);

        mContext = GwcNewFragment.this.getContext();

        initView(inflate);

        return inflate;
    }

    @Override
    public void onLazyLoad() {
        initData();
    }

    private void initView(View inflate) {
        ll_content = inflate.findViewById(R.id.ll_content);
        scroll_view = inflate.findViewById(R.id.scroll_view);
        tv_eidt = inflate.findViewById(R.id.tv_eidt);
        gwcEditView = inflate.findViewById(R.id.gwcEditView);
        setEdit();
        tv_eidt.setOnClickListener(this);

        setAllSelect();

        gwcEditView.getTv_go_confirem().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSelectData();
                System.out.println("gwcdatasize : " + selectData.size());
                submitDingdan();

            }
        });

        setDelete();
    }

    private void setDelete() {
        gwcEditView.getDelete().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSelectData();
                if (selectData == null || selectData.size() == 0) {
                    Toast.makeText(mContext, "请勾选数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                toDelete();
            }
        });
    }

    private void toDelete() {
//        selectData
        String id = "";
        for (int i = 0; i < selectData.size(); i++) {
            GwcBean2.DataBean.RecordsBean recordsBean = selectData.get(i);
            String idstr = recordsBean.getId();
            if (i == selectData.size() - 1) {
                id = id + idstr;
            } else {
                id = id + idstr + ",";
            }

        }

        if (TextUtils.isEmpty(id)) {
            Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = DataManager.BaseUrl + "mall/shopordercart/batchDeleteById?id=" + id;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.DELETE_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {

                    if (DataPares.isSucess(mContext, response)) {
                        Toast.makeText(mContext, "删除成功", Toast.LENGTH_SHORT).show();
                    }
                    //删除后刷新购物车
                    initData();
                } catch (Exception e) {

                }
                System.out.println("");
            }
        });
    }

    private void submitDingdan() {

        try {

            if (selectData == null | selectData.size() == 0) {
                Toast.makeText(mContext, "购物车不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            String cardProductId = "";
            for (int i = 0; i < selectData.size(); i++) {
                GwcBean2.DataBean.RecordsBean recordsBean = selectData.get(i);
                cardProductId = cardProductId + recordsBean.getProductId() + "," +
                        recordsBean.getAttributeId() + "," + recordsBean.getProductAmount() + ";";
            }

            String url = DataManager.BaseUrl + "mall/shoporder/getShopDiscountCouponsPage?" +
                    "cardProductId=" + cardProductId;
            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey, DataManager.getToken(mContext));
//        headMap.put(DataManager.AuthorizationKey,"Bearer 2af9350c-dad4-4e04-b5b9-6a931f9b7b0c");
            //todo 测试提交订单
            DataManager.toServer3(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try {

                        if (DataPares.isSucess(mContext, response)) {
                            Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
                            System.out.println("");
                            Intent intent = new Intent(mContext, ConfirmOrderActivity.class);
                            intent.putExtra("data", response);
//                        intent.putExtra("id",id);
                            startActivity(intent);
                        } else {
                            Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
                        }


                    } catch (Exception e) {

                    }
                }
            });
        } catch (Exception e) {

        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_eidt:
                isEdit = !isEdit;
                setEdit();
                break;

            case R.id.gwcEditView:

                break;

            case R.id.gwcEndView:
                break;
        }
    }

    private void setEdit() {
        if (isEdit) {//编辑状态文字显示完成
            tv_eidt.setText("完成");
        } else {//完成状态文字显示编辑
            tv_eidt.setText("编辑");
        }
        gwcEditView.setIsEdit(isEdit);
        setSingleDeleteIsVisible();
    }

    //isEdit
    private void setSingleDeleteIsVisible() {
        try {
            for (int i = 0; i < ll_content.getChildCount(); i++) {
                GwcItemView itemView = (GwcItemView) ll_content.getChildAt(i);
                itemView.setSingleDeleteIsVisible(isEdit);
            }

        } catch (Exception e) {

        }
    }

    public void initData() {
        String url = DataManager.BaseUrl_weicheng + "mall/shopordercart/findShopOrderCartList?userId=" +
                SPUtil.getDataForString(getActivity(), Constant.UserId, "");
        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put(DataManager.AuthorizationKey, DataManager.getToken(getContext()));
        DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headHashMap, new DataManager.GeResponse() {

            @Override
            public void onResponse(String response) {

                try {
                    GwcBean2 gwcBean = JSON.parseObject(response, GwcBean2.class);

                    records = gwcBean.getData().getRecords();
                    if (records == null || records.size() == 0) {
                        inflate.findViewById(R.id.nullView).setVisibility(View.VISIBLE);
                        scroll_view.setVisibility(View.GONE);
                        gwcEditView.setVisibility(View.GONE);
                        return;
                    } else {
                        inflate.findViewById(R.id.nullView).setVisibility(View.GONE);
                        scroll_view.setVisibility(View.VISIBLE);
                        gwcEditView.setVisibility(View.VISIBLE);
                    }
                    setData(records);
                    System.out.println();
                    //编辑模式控制删除按钮的显示
                    setSingleDeleteIsVisible();
                } catch (Exception e) {

                }
            }
        });
    }

    private void setData(List<GwcBean2.DataBean.RecordsBean> records) {
        try {
            ll_content.removeAllViews();
            gwcEditView.getCheckbox().setChecked(false);
            gwcEditView.setSumPrice(new BigDecimal(0));
            for (int i = 0; i < records.size(); i++) {
                GwcItemView itemView = new GwcItemView(mContext).setOnItemAllLIstener(onitemChangeLIstener);
                itemView.setFragment(this);
                itemView.setData(records.get(i));
                ll_content.addView(itemView);
            }
        } catch (Exception e) {
        }
    }

    private void setAllSelect() {
        gwcEditView.getCheckbox().setOnChangeLIstener(new OnChangeLIstener() {
            @Override
            public void onChangeLIstener() {
                isAllSelet = !isAllSelet;
                setItem();
                setSumPrice();
            }
        });
    }

    private void setItem() {
        try {
            for (int i = 0; i < ll_content.getChildCount(); i++) {
                GwcItemView itemView = (GwcItemView) ll_content.getChildAt(i);
                itemView.setIsAllSelect(isAllSelet);

            }


        } catch (Exception e) {

        }
    }

    private void isAllSelet() {
        try {
            for (int i = 0; i < ll_content.getChildCount(); i++) {
                GwcItemView itemView = (GwcItemView) ll_content.getChildAt(i);
                boolean isitemAllSelect = itemView.getIsAllSelect();
                if (!isitemAllSelect) {
                    isAllSelet = false;
                    return;
                }
            }


            isAllSelet = true;


        } catch (Exception e) {

        }
    }

    private void setSumPrice() {
        BigDecimal sumPrice = new BigDecimal(0);
        try {
            for (int i = 0; i < ll_content.getChildCount(); i++) {
                GwcItemView itemView = (GwcItemView) ll_content.getChildAt(i);
                boolean isitemAllSelect = itemView.getIsAllSelect();
                if (isitemAllSelect) {
                    selectData.add(itemView.getData());
//                    sumPrice = sumPrice + StrUtil.toBigDecimal(itemView.getData().getPrice());
                    sumPrice = sumPrice.add(StrUtil.toBigDecimal(itemView.getData().getPrice()));
                }
            }

            gwcEditView.setSumPrice(sumPrice);
        } catch (Exception e) {

        }

    }

    private void getSelectData() {
        selectData.clear();
        try {
            for (int i = 0; i < ll_content.getChildCount(); i++) {
                GwcItemView itemView = (GwcItemView) ll_content.getChildAt(i);
                boolean isitemAllSelect = itemView.getIsAllSelect();
                if (isitemAllSelect) {
                    selectData.add(itemView.getData());
                }
            }

        } catch (Exception e) {

        }
    }
}
